package com.gastronomy.service.impl;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.gastronomy.constant.Constant;
import com.gastronomy.dao.RoleDao;
import com.gastronomy.dao.UserDao;
import com.gastronomy.entity.DishesEntity;
import com.gastronomy.entity.Role;
import com.gastronomy.entity.User;
import com.gastronomy.service.DishesService;
import com.gastronomy.service.UserService;
import com.github.pagehelper.PageHelper;
@Service("userService")
public class UserserviceImpl implements UserService{
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RoleDao roleDao;
	@Resource
	private DishesService dishesService;
	/**
	 * 新增用户
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, String> addUser(User user,String roleId,String password2,MultipartFile picFile) {

		Map<String, String> resultMap = new HashMap<String, String>();
		if( user == null || user.getUserName()== null || user.getUserName().trim().equals("")|| user.getPassword() == null || user.getPassword().trim().equals("")){
			resultMap.put("registResult", "FAil");
			resultMap.put("errorMsg", "请输入正确的用户名和密码");
			return resultMap;
		}
		if(password2 == null || password2.trim().equals("")){
			resultMap.put("registResult", "FAil");
			resultMap.put("errorMsg", "请输入确认密码");
			return resultMap;
			
		}
		if(!user.getPassword().equals(password2)){
			resultMap.put("registResult", "FAil");
			resultMap.put("errorMsg", "两次密码输入的不一致");
			return resultMap;
		}
		if( user.getEmail() == null || user.getEmail().trim().equals("")){
			resultMap.put("registResult", "FAil");
			resultMap.put("errorMsg", "请输入邮箱");
			return resultMap;
		}
		if(roleId.equals("3")){
			if( user.getAddress() == null || user.getAddress().trim().equals("")){
				resultMap.put("registResult", "FAil");
				resultMap.put("errorMsg", "请输入商户地址");
				return resultMap;
			}
			if( user.getTelPhone() == null || user.getTelPhone().trim().equals("")){
				resultMap.put("registResult", "FAil");
				resultMap.put("errorMsg", "请输入商户电话");
				return resultMap;
			}
			if( user.getWorkTime() == null || user.getWorkTime().trim().equals("")){
				resultMap.put("registResult", "FAil");
				resultMap.put("errorMsg", "请输入商户工作时间");
				return resultMap;
			}
			if( user.getNickName() == null || user.getNickName().trim().equals("")){
				resultMap.put("registResult", "FAil");
				resultMap.put("errorMsg", "请输入商户名称");
				return resultMap;
			}
		}
		try {
			if(picFile!=null){
				String newFileName = dishesService.saveUploadPic(user,picFile);
				if(!newFileName.equals("FAIL")){
					user.setTopPic(File.separator+Constant.PIC_PATH+File.separator+user.getUserName()+File.separator+newFileName);
				}
			}
			
			Role role = roleDao.findRoleById(Integer.parseInt(roleId));
			if(role == null ){
				resultMap.put("registResult", "FAIL");
				resultMap.put("errorMsg", "不存在改权限的用户");
				return resultMap;
			}
			user.setCreateTime(new Timestamp(new Date().getTime()));
			user.setRole(role);
			if(roleId.equals("3")){
				user.setUserType(0);
				userDao.addBusinessUser(user);
			}else
				userDao.addUser(user);
			resultMap.put("registResult", "SUCCESS");
		} catch (Exception e) {
			resultMap.put("registResult", "FAIL");
			resultMap.put("errorMsg", e.getMessage());
		}
		return resultMap;
	}

	@Override
	public Map<String, String> queryUser(User user) {
		Map<String, String> resultMap = new HashMap<String, String>();
		if( user == null || user.getUserName()== null || user.getUserName().trim().equals("")|| user.getPassword() == null || user.getPassword().trim().equals("")){
			resultMap.put("loginResult", "FAIL");
			resultMap.put("errorMsg", "请输入正确的用户名和密码");
			return resultMap;
		}
		
		User user2 = userDao.findUserByNameAndPwd(user.getUserName(), user.getPassword());
		if(user2!=null){
			if(user2.getUserType() == 0){
				//冻结状态，无法登陆
				resultMap.put("loginResult", "FAIL");
				resultMap.put("errorMsg", "您的账户正在审核中，请稍后登录！");
				return resultMap;
			}
			user.setRole(user2.getRole());
			resultMap.put("loginResult", "SUCCESS");
		}else {
			resultMap.put("loginResult", "FAIL");
			resultMap.put("errorMsg", "用户名或密码错误");
		}

		return resultMap;
	}

	@Override
	public User queryUserById(String id) {
		Integer userId = 0;
		try {
			userId = Integer.parseInt(id);
		} catch (Exception e) {
			System.out.println("queryUserById id不正确");
			return null;
		}
		return userDao.queryUserById(userId);
	}

	@Override
	public List<User> listUsers(Integer[] roleTypes) {
		return userDao.litsUsers(roleTypes);
	}

	@Override
	public Map<String, String> lockUser(String ids, User user) {
		Map<String, String> resultMap = new HashMap<String, String>();
		if( user == null || user.getRole().getId() != 2){
			resultMap.put("lockResult", "FAil");
			resultMap.put("errorMsg", "您没有权限进行此操作操作");
			return resultMap;
		}
		
		String [] allIds = ids.split(",");
		
		try {
			userDao.lockUsers(allIds);
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
			resultMap.put("lockResult", "FAil");
			resultMap.put("errorMsg", "冻结失败，请稍后再试");
			return resultMap;
		}
		resultMap.put("lockResult", "SUCCESS");
		return resultMap;
	}
	
	@Override
	public Map<String, String> unLockUser(String ids, User user) {
		Map<String, String> resultMap = new HashMap<String, String>();
		if( user == null || user.getRole().getId() != 2){
			resultMap.put("unLockResult", "FAil");
			resultMap.put("errorMsg", "您没有权限进行此操作操作");
			return resultMap;
		}
		
		String [] allIds = ids.split(",");
		
		try {
			userDao.unLockUsers(allIds);
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
			resultMap.put("unLockResult", "FAil");
			resultMap.put("errorMsg", "解冻失败，请稍后再试");
			return resultMap;
		}
		resultMap.put("unLockResult", "SUCCESS");
		return resultMap;
	}

	@Override
	public List<User> sortBusiness(String type, String sortType, String nickName, String currentPage ,int pageSize) {
		//type==A，查询
		//type==B，排序，sortType==nickName：按名称排序，sortType==createTime：按发布时间排序
		//type==C，加载更多
		List<User> userList = new ArrayList<User>();
		if(nickName==null){
			nickName = "";
		}
		if(sortType==null){
			sortType = "createTime";
		}
		if(type==null){
			type = "A";
		}
		if(type.equals("A")||type.equals("B")){
			currentPage = "1";
		}
		sort(currentPage,pageSize);
		if(sortType.equals("nickName")){
			userList = userDao.sortBusinessByNickName(nickName);
		}else if(sortType.equals("createTime")){
			userList = userDao.sortBusinessByCreateTime(nickName);
		}
		return userList;
	}

	@Override
	public User getUserByLoginName(String loginName) {
		return userDao.getUserByLoginName(loginName);
	}

	public void sort(String currentPage,int pageSize){
		Integer page = 1;
		try {
			if(currentPage==null||currentPage.equals("")){
				currentPage = "1";
			}
			page = Integer.parseInt(currentPage);
		} catch (Exception e) {
			System.out.println("转化错误");
			page = 1;
		}
		PageHelper.startPage(page, pageSize);
	}
}

